using System;
using System.ComponentModel.Design;
using System.Globalization;
using System.IO;
using EnvDTE;

namespace VSSDKAssist.Assets.Helpers
{
	/// <summary>
	/// Team Foundation Helper
	/// </summary>
    public static class TFSHelper
    {
		#region Public Implementation
		/// <summary>
		/// Checks the out file.
		/// </summary>
		/// <param name="vs">The vs.</param>
		/// <param name="filePath">The file path.</param>
		public static void CheckOutFile(_DTE vs, string filePath)
		{
			if(vs == null)
				throw new ArgumentNullException("vs");

			if(File.Exists(filePath))
			{
				if(vs.SourceControl.IsItemUnderSCC(filePath) &&
					!vs.SourceControl.IsItemCheckedOut(filePath))
				{
					bool checkout = vs.SourceControl.CheckOutItem(filePath);
					if(!checkout)
					{
						throw new CheckoutException(
							string.Format(CultureInfo.CurrentCulture, Properties.Resources.CheckoutException, filePath));
					}
				}
				else
				{
					// perform an extra check if the file is read only.
					if(IsReadOnly(filePath))
					{
						ResetReadOnly(filePath);
					}
				}
			}
		} 
		#endregion

		#region Private Implementation
		private static bool IsReadOnly(string path)
		{
			return (File.GetAttributes(path) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly;
		}

		private static void ResetReadOnly(string path)
		{
			File.SetAttributes(path, File.GetAttributes(path) ^ FileAttributes.ReadOnly);
		}
		#endregion
    }
}